//
//  RLHud.m
//  CCKit
//
//  Created by tucici on 2019/4/12.
//  Copyright © 2019 tucici. All rights reserved.
//

#import "RLHud.h"
@interface RLHud ()
@property (nonatomic, strong) UIActivityIndicatorView *hudView;
@property (nonatomic, strong) UILabel *label;
@end
@implementation RLHud
static RLHud * _RLHud;
static dispatch_once_t hudtoken;
+ (instancetype)hud
{
    if (!_RLHud)
    {
        dispatch_once(&hudtoken, ^{
            _RLHud = [[RLHud alloc] init];
        });
    }
    return _RLHud;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.bounds = CGRectMake(0, 0, 100, 100);
        self.layer.cornerRadius = 5.0;
        self.layer.masksToBounds = YES;
        self.backgroundColor = [UIColor colorHex:@"#000000" :0.8];
        self.windowLevel = UIWindowLevelAlert;
        self.rootViewController = [[UIViewController alloc] init];
        self.rootViewController.view.hidden = YES;
        [self makeKeyAndVisible];
    }
    return self;
}
- (UIActivityIndicatorView *)hudView
{
    if (!_hudView)
    {
        _hudView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:0];
        _hudView.bounds = CGRectMake(0, 0, self.bounds.size.width / 2, self.bounds.size.width / 2);
        _hudView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_hudView];
        [self setupHudViewLayout];
    }
    return _hudView;
}
- (UILabel *)label
{
    if (!_label)
    {
        _label = [[UILabel alloc]init];
        _label.backgroundColor = [UIColor clearColor];
        _label.numberOfLines = 0;
        _label.textColor = [UIColor whiteColor];
        _label.textAlignment = NSTextAlignmentCenter;
        _label.font = [UIFont systemFontOfSize:15 weight:UIFontWeightLight];
        _label.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_label];
        [self setupLabelLayout];
    }
    return _label;
}

- (void)setColor:(UIColor *)color
{
    if (_color != color)
    {
        _color = color;
        self.hudView.color = color;
        self.label.textColor = color;
    }
}

- (void)setTimes:(CGFloat)times
{
    if (_times != times)
    {
        _times = times;
        
        if (self.hudView.bounds.size.width * times <= self.bounds.size.width )
        {
            self.hudView.transform = CGAffineTransformMakeScale(times, times);
        }
    }
}

- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];
    for (NSLayoutConstraint * constraint in [[self constraints] reverseObjectEnumerator])
    {
        if ((constraint.firstAttribute == NSLayoutAttributeWidth || constraint.firstAttribute == NSLayoutAttributeHeight) && [constraint.firstItem isEqual:self])
            [self removeConstraint:constraint];
    }
    NSLayoutConstraint * w = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:self.bounds.size.width];
    NSLayoutConstraint * h  = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:self.bounds.size.height];
    [self addConstraints:@[w,h]];
}

- (void)setupHudViewLayout
{
    NSLayoutConstraint * centerX  = [NSLayoutConstraint constraintWithItem:self.hudView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    
    
    NSLayoutConstraint * centerY = [NSLayoutConstraint constraintWithItem:self.hudView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    
    
    NSLayoutConstraint * width = [NSLayoutConstraint constraintWithItem:self.hudView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:50];
    
    
    NSLayoutConstraint * height = [NSLayoutConstraint constraintWithItem:self.hudView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:50];
    
    [_hudView addConstraints:@[width, height]];
    [self addConstraints:@[centerX,centerY]];
}
- (void)setupLabelLayout
{
    NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.hudView attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
    
    NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
    
    NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1 constant:0];
    
    NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
    [self addConstraints:@[top,left,right,bottom]];
}

- (void)updateHudViewLayout
{
    self.bounds = CGRectMake(0, 0, 100, 100);//hud的bounds初始化
    CGSize size = [self.label.text size:self.label.font :self.bounds.size.width];
    [self autoZoom:size.height];//根据title自动锁放Hud
    
    for (NSLayoutConstraint * constraint in [[self constraints] reverseObjectEnumerator])
    {
        if ((constraint.firstAttribute == NSLayoutAttributeTop || constraint.firstAttribute == NSLayoutAttributeCenterY) && [constraint.firstItem isEqual:self.hudView])
            [self removeConstraint:constraint];
    }
    
    NSLayoutConstraint *newContraint;
    if ([RLHud hud].label.hidden == YES)
        newContraint = [NSLayoutConstraint constraintWithItem:self.hudView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    else
        newContraint = [NSLayoutConstraint constraintWithItem:self.hudView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:10];
    [self addConstraint:newContraint];
}

//根据title自动缩放Hud
- (void)autoZoom:(CGFloat)height
{
    if (height > self.bounds.size.height - 50)
    {
        self.bounds = CGRectMake(0, 0, self.bounds.size.width + 18, self.bounds.size.height + 18);
        CGSize size = [self.label.text size:self.label.font :self.bounds.size.width];
        [self autoZoom:size.height];
    }
    
}
+ (void)startHud
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [RLHud hud].hidden = NO;
        [[RLHud hud].hudView startAnimating];
        [RLHud hud].label.hidden = YES;
        [RLHud hud].label.text = @"";
        [[RLHud hud] updateHudViewLayout];
    });
}

+ (void)stopHud
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [RLHud hud].hidden = YES;
        [[RLHud hud].hudView stopAnimating];
        [RLHud hud].label.hidden = YES;
        [RLHud hud].label.text = @"";
    });
}

+ (void)startHud:(NSString *)title
{
    [RLHud hud].hidden = NO;
    [[RLHud hud].hudView startAnimating];
    [RLHud hud].label.hidden = NO;
    [RLHud hud].label.text = title;
    [[RLHud hud] updateHudViewLayout];
}

+ (void)startHud:(NSString *)title stopTime:(int)time handle:(nullable void (^)(void))block
{
    if (!title)
        [self stopHud:block];
    else if([title length] <= 0)
        [self stopHud:block];
    else if(time <= 0)
        [self stopHud:block];
    else
    {
        [self startHud:title];
        [self performSelector:@selector(stopHud:) withObject:block afterDelay:time];
    }
}
+ (void)stopHud:(nullable void(^) (void))block
{
    [self stopHud];
    [[RLHud hud].hudView isAnimating];
    if (block)
    {
        block();
    }
}
@end
